//
//  TRFindListView.m
//  WeiMiLan
//
//  Created by anan on 14/11/22.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRFindNewsListView.h"
#import "SDCycleScrollView.h"
#import "MJExtension.h"
#import "TRAdsModel.h"
#import "UIView+LYLoadingView.h"

@interface TRFindNewsListView () <SDCycleScrollViewDelegate>
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSMutableArray *imagesURLStrings;
@end

@implementation TRFindNewsListView{
    int historyY;
}

- (NSArray *)modelArray {
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (NSMutableArray *)imagesURLStrings {
    if (_imagesURLStrings == nil) {
        _imagesURLStrings = [[NSMutableArray alloc]init];
    }
    return _imagesURLStrings;
}
- (void)reload
{
    // 1.注册
    UINib *nib1 = [UINib nibWithNibName:@"TRFindViewTableViewCell" bundle:nil];
    [self.tableView registerNib:nib1 forCellReuseIdentifier:@"TRFindViewTableViewCell"];
    self.tableView.backgroundColor = [UIColor whiteColor];
    
   [self loadAds];
    
    [self addHeader];
    [self addFooter];
   
    self.tableView.frame = CGRectMake(0, 2, self.width, self.height);
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 6, 0);
    
    
    
}

- (void)loadAds {
    
   
    
   AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/guanggaowei" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *array = responseObject[@"contents"];
        self.modelArray = [TRAdsModel objectArrayWithKeyValuesArray:array];
        NSMutableArray *arrays = [NSMutableArray array];
        for (NSInteger i = 0; i < 4; i++) {
            [arrays addObject:self.modelArray[i]];
        }
        [self.modelArray removeAllObjects];
        [self.modelArray addObjectsFromArray:arrays];
        for (TRAdsModel *ads in self.modelArray) {
            [self.imagesURLStrings addObject:ads.advertisementPic];
           // NSLog(@"--------%@",self.imagesURLStrings);
        }
        [self addScrollAds];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:STR_MSG_NETWORK_ERROR];
    }];
}
- (void)refresh
{
    
    
    [refreshHeaderView beginRefreshing];
    [refreshHeaderView endRefreshing];
    //[self performSelector:@selector(doneWithView:) withObject:nil afterDelay:0.7f];

}

- (void)loadData:(int)num
{
 //   [MBProgressHUD showMessage:@"加载中..."];
    [self showLoadingViewWithText:@"加载中..."];
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSDate *dateEnd = [NSDate date];
    NSDate *dateStart = [NSDate dateWithTimeIntervalSince1970:[dateEnd timeIntervalSince1970]-24*60*60];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:[dateStart ql_ToStringWithFormat:@"yyyyMMddHHmmss"] forKey:@"BEGIN_DATE"];
    [dic setObject:[dateEnd ql_ToStringWithFormat:@"yyyyMMddHHmmss"] forKey:@"END_DATE"];
    [dic setObject:QLIntToNumber(num) forKey:@"PAGE_NUM"];
    [dic ql_setInterge:[userInfo ql_intForKey:@"ID"] forKey:@"userId"];
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/Package?type=1023" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
            if (num==1) {
                //第一页
                if ([responseObject[@"PACKAGE_RSP"][@"PACKAGE"] isKindOfClass:[NSDictionary class]]) {
                    [self.contents addObject:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                }else{
                    self.contents = [NSMutableArray arrayWithArray:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                }
            }else{
                [self.contents addObjectsFromArray:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
            }
            
            NSDictionary *pageInfo = responseObject[@"PAGE_INFO"];
            self.nextPage = [pageInfo ql_intForKey:@"NEXT"];
            self.currentPage = [pageInfo ql_intForKey:@"NUMBER"];
            if (self.nextPage>self.currentPage) {
                refreshFooterView.isend = NO;
            }else{
                refreshFooterView.isend = YES;
            }
        }
        
//        NSLog(@"%@---",[NSString stringWithFormat:@"%@",responseObject[@"PAGE_INFO"][@"COUNT"]]);
//        
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"kHomeCommetnCountChanged" object:nil userInfo:@{@"count": [NSString stringWithFormat:@"%@",responseObject[@"PAGE_INFO"][@"COUNT"]]}];
        
      //  [MBProgressHUD hideHUD];
        [self dismissLoadingView];
        [self performSelector:@selector(doneWithView:) withObject:nil afterDelay:0.2f];
         [self.cycleScrollView clearCache];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       // [MBProgressHUD hideHUD];
        [self dismissLoadingView];
        [SVProgressHUD showErrorWithStatus:STR_MSG_NETWORK_ERROR];
        [self performSelector:@selector(doneWithView:) withObject:nil afterDelay:0.2f];
         [self.cycleScrollView clearCache];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    long count = self.contents==nil?0:self.contents.count;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRFindViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRFindViewTableViewCell"];
    if (cell == nil) {
        cell = [[TRFindViewTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRFindViewTableViewCell"];
    }
    NSDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    cell.viewController = self.viewController;
    [cell setNeedsDisplay];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRFindViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRFindViewTableViewCell"];
    if (cell == nil) {
        cell = [[TRFindViewTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRFindViewTableViewCell"];
    }
    NSDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    cell.viewController = self.viewController;
    return [cell getHeight];
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dic = [self.contents objectAtIndex:indexPath.row];
    [QLPlayerManager openProductDetailWithId:[dic ql_stringForKey:@"ID"] viewController:self.viewController];
}

- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    refreshFooterView = footer;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadData:self.nextPage];
    };
}

- (void)loadFirstData
{
    [refreshHeaderView beginRefreshing];
    [refreshHeaderView endRefreshing];
  //  [self performSelector:@selector(doneWithView:) withObject:nil afterDelay:0.2f];
}

- (void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    refreshHeaderView = header;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        [self loadData:1];
    };
    [self performSelector:@selector(loadFirstData) withObject:nil afterDelay:0.2];
}

- (void)doneWithView:(id)sender
{
    // 刷新表格
    [self.tableView reloadData];
    [refreshFooterView endRefreshing];
    [refreshHeaderView endRefreshing];
}

#pragma mark - QLMaskNodataViewOnClickDelegate
-(void)onClick:(id)sender
{
    [QLMaskUtil hideNodataMaskWithView:self.tableView];
    [refreshHeaderView beginRefreshing];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    TRFindViewController *fvc = (TRFindViewController*)self.viewController;
    if (historyY+150<targetContentOffset->y)
    {
        [fvc fullScreen];
    }
    else if(historyY-150>targetContentOffset->y)
    {
        [fvc fullScreenExit];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    historyY = scrollView.contentOffset.y;
}

- (void)addScrollAds {

    CGFloat w = self.width;
    
    self.tableView.tableHeaderView.backgroundColor = [UIColor whiteColor];
    
    //  --- 创建不带标题的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(2, 2, w - 4, 130) imageURLStringsGroup:self.imagesURLStrings];
    
    cycleScrollView.infiniteLoop = YES;
    cycleScrollView.delegate = self;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    //  self.tableView.tableHeaderView = cycleScrollView;
 //   [self addSubview:cycleScrollView];
    self.tableView.tableHeaderView = cycleScrollView;

    self.cycleScrollView = cycleScrollView;
  //  self.cycleScrollView.dotColor = [UIColor grayColor];
    self.cycleScrollView.pageControlDotSize = CGSizeMake(6, 6);
    //         --- 轮播时间间隔，默认1.0秒，可自定义
    //cycleScrollView.autoScrollTimeInterval = 4.0;
}

#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    TRAdsModel *adsModel = self.modelArray[index];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"kLoadAds" object:nil userInfo:@{@"web" : adsModel.url}];
    
   // NSLog(@"---点击了第%ld张图片", index);
}
@end
